import React, {useCallback, useEffect, useMemo, useState} from "react"
import {Pageable} from "../../utils/Page";
import {createGoodsBrandGroup, queryGoodsBrandGroups, QueryGoodsBrandGroupsResponse, updateGoodsBrandGroup} from "../../apis/GoodsBrandGroupApi";
import AuthorizationResource from "../../components/AuthorizationResource";
import {Button, ConfigProvider, Form, Input, Table} from "antd";
import {EditOutlined, PlusOutlined} from "@ant-design/icons";
import {castFilterValue, mergePaginationAndPageable, useTableSearchTextColumnProps} from "../../utils/AntdTableUtils";
import {QueryGoodsResponse} from "../../apis/GoodsApi";
import DataPageLayout from "../../components/DataPageLayout";
import FormDrawer from "../../components/FormDrawer";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";

export interface GoodsBrandGroupProps {

}

export interface GoodsBrandGroupFormData {
    name: string
}

const GoodsBrandGroupPage: React.FC<GoodsBrandGroupProps> = (props) => {
    const [openAddDrawer, setOpenAddDrawer] = useState(false)
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryGoodsBrandGroupsResponse[]>([])
    const [searchNameText, setSearchNameText] = useState<string>()
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)

    let query = useCallback(()=>{
        setLoading(true)
        queryGoodsBrandGroups({name: searchNameText,}, pageable).then(response => {
            setTotalElements(response.data.totalElements)
            setData(response.data.content)
        }).finally(() => {
            setLoading(false)
        })
    },[...pageable.toDependencyList(), searchNameText,]);

    const [editingItemId, setEditingItemId] = useState<number>()
    const editingItem = useMemo(() => {
        return data.find(it => it.id === editingItemId)
    }, [editingItemId,data]);

    useEffect(() => {
        query()
    }, [query]);
    let nameSearchProps = useTableSearchTextColumnProps<QueryGoodsResponse>("name", {
        placeholder: "名称"
    });

    function buildFormItems() {
        return <>
            <Form.Item label={"名称"} name="name" rules={[{required: true}]}>
                <Input/>
            </Form.Item>
        </>
    }

    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["货品_品牌分组_查询"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>新增品牌分组</Button>
        </AuthorizationResource>}>
            <ConfigProvider componentSize={"small"}>
            <Table loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setSearchNameText(castFilterValue(filters.name))
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
            }}>
                <Table.Column dataIndex={"name"} title={"名称"} {...nameSearchProps}/>
                <Table.Column<QueryGoodsBrandGroupsResponse> dataIndex={"brandAmount"} title={"品牌数量"}/>
                <Table.Column<QueryGoodsBrandGroupsResponse> title={"操作"} render={(_, item) => {
                    return <AuthorizationResource authorities={["货品_品牌_修改"]}><Button type={"link"}
                                                                                                   onClick={() => {
                                                                                                       setEditingItemId(item.id)
                                                                                                   }}>
                        <EditOutlined/>
                    </Button></AuthorizationResource>
                }}/>
            </Table>
            </ConfigProvider>
        </DataPageLayout>
        <FormDrawer<GoodsBrandGroupFormData> onClose={() => setOpenAddDrawer(false)}
                                        title={"新增品牌分组"}
                                        onConfirm={async (values) => {
                                            return createGoodsBrandGroup(values).then(() => {
                                                setOpenAddDrawer(false)
                                                query()
                                            })
                                        }}
                                        open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
        <FormDrawer<GoodsBrandGroupFormData> open={!!editingItem} title={"修改品牌分组"} onClose={() => {
            setEditingItemId(undefined)
        }} onConfirm={async (values) => {
            return updateGoodsBrandGroup(editingItemId!!, values).then(() => {
                query()
                setEditingItemId(undefined)
            })
        }} initialValues={editingItem}>
            {buildFormItems()}
        </FormDrawer>
    </>
}

export default observerDashboardPageWrapper(GoodsBrandGroupPage,"goods/brands/groups","货品品牌组")